<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

define('SOAP',       'http://114.215.209.224:8045/'); //测试
//define('SOAP',       'http://121.199.13.50:8088/'); //正式
define('SOAP_HEADER','http://168zght.com/webservices/');
//require_once '../PHPExcel/IOFactory.php';
class CI_Core{
	private $tbname;
	private $dbname='';
	public  $ci;
	public  $db;
	
	function __construct(){
		error_reporting(E_ERROR);
		$this->ci =& get_instance();
		$this->ci->load->helper('url');
		$this->ci->load->library('session');
		$this->ci->load->library('pagination');
	}
	/***链接数据库 ***/
	public function database($_db,$close=false){
		if(!empty($this->dbname) && $close){//forece close previous connection
			$this->db->close();
		}
		$this->dbname=$_db;
		return $this->db=$this->ci->load->database($_db,true);
	}	
	/*** 判断后台登陆状态 ***/
	public function checkLogin(){
		if(!$this->ci->session->userdata('login')) header('Location: '.WEB.'welcome/login?force=1');
	}
	/*** 获取相对路径 ***/
	private function getRelatePath(){
		$base = dirname(dirname(BASEPATH));
		$base = str_replace($base,'',FCPATH); 
		return $base; //return project/ht/admin
	}
	
	/*** 打开表 ***/
	public function open($table){
		$this->tbname=$table;
	}
	/**获取一条记录**/
	public function get_one($flids='*',$tj_arr=array(),$table='',$condition=array()){
		$this->db->select($flids);
		if(array_key_exists('order',$condition)) $this->db->order_by($condition['order']);
	    if(array_key_exists('group',$condition)) $this->db->group_by($condition['group']);		
		if(array_key_exists('limit',$condition)) {
			$arr = explode(",",$condition['limit']);
			$this->db->limit($arr[0],$arr[1]);
		}
        $query = $this->db->get_where($table,$tj_arr);
        if ($row = $query->row_array()){
        	return $row;
        }
        return array();
	}
	/** 获取所有记录**/
	public function get_all($flids='*',$tj_arr=array(),$table='',$condition=array()){  //$tj_arr����
	
		$tj1=array();
		foreach($tj_arr as $k=>$v){
			if(isset($v)&&!empty($v)){
				$tj1[$k]=$v;
			}
		}
		if(empty($table))$table=$this->tbname;
		$this->db->from($table.' as b');
		if(array_key_exists('join',$condition)){
	    	$this->db->join($condition['join'].' as a',$condition['on'],'left'); 
	    	if(array_key_exists('a_fields',$condition)) $a=$condition['a_fields']; else $a="a.*";
	    	if(array_key_exists('b_fields',$condition)) $b=$condition['b_fields']; else $b="b.*";
	    	$this->db->select("b.id as cid,$b,$a");
    	}else{
      		$this->db->select($flids);
    	}
		#echo '<pre>';print_R($condition);exit;
	    if(array_key_exists('limit',$condition)) $this->db->limit($condition['limit']);
	    if(array_key_exists('page_limit',$condition)) $this->db->limit($condition['page_limit'][0],$condition['page_limit'][1]);
	    if(array_key_exists('order',$condition)) $this->db->order_by($condition['order']);
	    if(array_key_exists('group',$condition)) $this->db->group_by($condition['group']);
		
	    if(array_key_exists('wherein',$condition)){
		  	foreach($condition['wherein'] as $k=>$v){
		  		$this->db->where_in($k,$v);
		  	}
		  }
	  //LIKE���
		if(array_key_exists('like',$condition)){
			foreach($condition['like'] as $k=>$v){
				if(!empty($v)){
					$this->db->like($k,$v);
				}
			}
		}
		if(array_key_exists('notlike',$condition)){
			foreach($condition['nolike'] as $k=>$v){
				if(!empty($v)){
					$this->db->not_like($k,$v);
				}
			}
		}
		if(array_key_exists('orderby',$condition)){
		  	foreach($condition['orderby'] as $k=>$v){
		  		$this->db->order_by($k,$v);
		  	}
		  }
	    if(array_key_exists('orwhere',$condition)){
		  	foreach($condition['orwhere'] as $k=>$v){
		  		$this->db->or_where($k,$v);
		  	}
		}
		if($tj1==array()){
			$query = $this->db->get();
		}else{
			$query = $this->db->get_where('',$tj1);
		}
		$rows=$query->result_array();
		return $rows;
	}
	/***修改**/
	public function edit($table){
		$params['id']=$this->ci->input->get('id');
		if(!empty($params['id']) && $params['id'] > 0){
			$id = $params['id'];
			$data['rs'] = $this->get_one('*',array('id'=>$id),$table);
			if(!$data['rs']){
				exit('{"status":"ERROR","msg":"ID��Ч!"}');
			}
		}
		return $data['rs'];
	}
	/*** 保存 ***/
	public function write($arr,$table){
		$id=$this->ci->input->post('id');
		if(isset($id)&&!empty($id)){ 
			$this->db->where('id', $id);
			$this->db->update($table,$arr);
		}else{
			$this->db->insert($table,$arr);
			$id = $this->db->insert_id();
		}
		ob_clean();
		
		if($this->db->affected_rows()>0){
	      echo '{"status":"OK","msg":"执行成功","id":"'.$id.'"}';
	    }else{
	      echo '{"status":"ERROR","msg":"执行失败"}';
	    }
		return $id;
   }
   /** 前台获取DATAGRID列表 **/
	public function front_get_list($args=array(),$parameter=array(),$pagesize,$nowindex,$def_sort='b.id'){
		$options=array();
		foreach($args as $k=>$v){
			if($v=='value-0'){
				if(strstr($k,'.'))
					$options['conditions'][$k]=0;
				else
					$options['conditions']['b.'.$k]=0;
			}
			else if(strstr($v,'time-')){
			  $item=strtotime($this->request(array_pop(explode(':',$v))));
			}else if(strstr($v,'value-')){
			 	$item=array_pop(explode('-',$v));
			}else{
			 	$item=$this->request($v);
			}
			if(isset($item)&&!empty($item)){
				if(strstr($k,'.'))
				 	$options['conditions'][$k]=$item;
				 else
					$options['conditions']['b.'.$k]=$item;
			}
			
		}
		$data['total_rows']=$this->count_rows($options,$parameter);//get total rows
		#echo '<pre>';print_R($parameter);exit;
		$data['result']   =$this->search($options,$pagesize,($nowindex-1)*$pagesize,$parameter,'*');//get result
	    return $data;
	}
   
   /** 获取列表（分页） **/
	function get_list($args=array(),$parameter=array(),$def_sort='b.id',$sum='*'){		
		$data=array();
		$pagesize = $this->ci->input->post('rows');         //page size
		$curPage  = $this->ci->input->post('page');         //current page
		$field    = $this->ci->input->post('sort');
		$sort     = empty($field)?$def_sort:'b.'.$field;    //field for ordering
		$order    = $this->ci->input->post('order');        //method for ordering
		$start    = $this->ci->input->post('start');
		$options = array('order'=>$order,'sort'=>$sort);
		//$options = array('order_multi'=>$order);
		foreach($args as $k=>$v){
			if($v=="value:0"){
				$item='0';
			}elseif(strstr($v,'time:')){
			  $t=$this->request(array_pop(explode(':',$v)));
			  $item=strtotime($t);
			}else if(strstr($v,'value:'))
			  $item=array_pop(explode(':',$v));
			else
			  $item=$this->request($v);
			  
			if($item==='0'||(isset($item)&&!empty($item))){
				if(strstr($k,'.'))
				 	$options['conditions'][$k]=$item;
				 else
					$options['conditions']['b.'.$k]=$item;
			}
		}
		
		$data['total_rows']=$this->count_rows($options,$parameter);//get total rows
		$data['result']   =$this->search($options,$pagesize,$curPage?($curPage-1)*$pagesize:$start,$parameter,$sum);//get result
	  	return $data;
	}
	
	//统计方法
	function count_total($args=array(),$parameter=array(),$sum_flid='sum(total_price) as total_price',$r=1){		
		$data=array();
		$pagesize = $this->ci->input->post('rows');         //page size
		$curPage  = $this->ci->input->post('page');         //current page
		$field    = $this->ci->input->post('sort');
		$sort     = empty($field)?$def_sort:'b.'.$field;    //field for ordering
		$order    = $this->ci->input->post('order');        //method for ordering
		$start    = $this->ci->input->post('start');
		$options = array('order_multi'=>$order);
		foreach($args as $k=>$v){
			if($v=="value:0"){
				$item='0';
			}elseif(strstr($v,'time:')){
			  $t=$this->request(array_pop(explode(':',$v)));
			  $item=strtotime($t);
			}else if(strstr($v,'value:'))
			  $item=array_pop(explode(':',$v));
			else
			  $item=$this->request($v);
			  
			if($item==='0'||(isset($item)&&!empty($item))){
				if(strstr($k,'.'))
				 	$options['conditions'][$k]=$item;
				 else
					$options['conditions']['b.'.$k]=$item;
			}
		}
		$this->db->from($this->tbname.' as b');
		$this->db->select("$sum_flid");
		$query = $this->_query($options,$parameter,true);
		$row   = $r==1?$query->row_array():$query->result_array();;
		return $row;
		
	}
	//POST
	public function request($arg){
		$item   = $this->ci->input->post($arg);
		$get   = $this->ci->input->get($arg);
		$params = $this->ci->uri->uri_to_assoc();
		if(empty($item)) $item=isset($params[$arg])?$params[$arg]:(isset($get)?$get:'');
		return $item;
	}

	/** 统计行 **/
	public function count_rows($options = array(),$parameter=array()){
		$this->db->from($this->tbname.' as b');
		if(array_key_exists('join',$parameter)){
		  if(array_key_exists('a_fields',$parameter)) $a=$parameter['a_fields']; else $a="a.*";
	      if(array_key_exists('b_fields',$parameter)) $b=$parameter['b_fields']; else $b="b.*";
		  $this->db->select("a.id as cid,$b,$a".(array_key_exists('alias',$parameter)?','.implode(' , ',$parameter['alias']):''));
		}else
		  $this->db->select('*');
		if(array_key_exists('limit', $parameter)) $this->db->limit($parameter['limit']);
		//unset($parameter['limit']);
		$sql = $this->_query($options,$parameter,false);
		#echo $sql;exit;
		$sql = "select count(*) as total_rows from($sql) total_table";
		$query=$this->db->query($sql);
		$row=$query->row_array();
		$this->db->_reset_select();
		return $row['total_rows'];
	}
	/** ������¼ **/
	private function search($options = array(),$count=20,$offset=0,$parameter=array()){
		if(!is_array($options)){return array();}
		
		if($count){$this->db->limit((int)$count, (int)$offset);}
		if(array_key_exists('join',$parameter)){
		  if(array_key_exists('a_fields',$parameter)) $a=$parameter['a_fields']; else $a="a.*";
	      if(array_key_exists('b_fields',$parameter)) $b=$parameter['b_fields']; else $b="b.*";
		  $this->db->select("a.id as cid,$b,$a".(array_key_exists('alias',$parameter)?','.implode(' , ',$parameter['alias']):''));
		}else
		  $this->db->select('*');
		$this->db->from($this->tbname.' as b');
		$query = $this->_query($options,$parameter);
		$rows = array();
		foreach($query->result_array() as $row){
			$rows[] = $row;
		}
		return $rows;
		 
	}
	
	/** ���ɲ�ѯ��� **/
	private function _query($options = null,$parameter=array(),$execute=true){
		if(array_key_exists('order_multi',$options)){
			foreach($options['order_multi'] as $v){
		  		$this->db->order_by($v['column'],$v['dir']);
		  	}
		}
		if(count($parameter)!=0){
			//JOIN���
			if(array_key_exists('join',$parameter)){
				$this->db->join($parameter['join'].' as a',$parameter['on'],'left');
			}
		}	
		
		 
		if(!empty($options['conditions'])){
				if(count($options['conditions'])!=0){
					foreach($options['conditions'] as $k=>$v){
						if(isset($v)&&!empty($v)){
							$this->db->where($k,$v);
						}
						if($v==='0'){
							$this->db->where($k,$v);
						}
					}
				}
			}
		if(count($parameter)!=0){
			//LIKE���
			if(array_key_exists('like',$parameter)){
				foreach($parameter['like'] as $k=>$v){
					$like_value=$this->request($v);
					if(!empty($v)){
						$this->db->like($k,$v);
					}
				}
			}
		//NOTLIKE���
			if(array_key_exists('notlike',$parameter)){
				foreach($parameter['notlike'] as $k=>$v){
					//$like_value=$this->request($v);
					if(!empty($v)){
						$this->db->not_like($k,$v);
					}
				}
			}
		  //GROUP BY���
		  if(array_key_exists('groupby',$parameter)){
			foreach($parameter['groupby'] as $k=>$v){
		  		$this->db->group_by($v);
		  	}
		  }
		  //ORDER BY���
		  if(array_key_exists('orderby',$parameter)){
		  	foreach($parameter['orderby'] as $k=>$v){
		  		$this->db->order_by($k,$v);
		  	}
		  }
		  //where in
		  if(array_key_exists('wherein',$parameter)){
		  	foreach($parameter['wherein'] as $k=>$v){
		  		if($v!='') $this->db->where_in($k,$v);
		  	}
		  }
		   if(array_key_exists('orwhere',$parameter)){
		  	foreach($parameter['orwhere'] as $k=>$v){
		  		$this->db->or_where($k,$v);
		    }
		  }
		  if(array_key_exists('wheresql',$parameter)){
		  	foreach($parameter['wheresql'] as $v){
		  		$this->db->where($v);
		  	}
		  } 
		} 
		//if(array_key_exists('limit',$parameter)) $this->db->limit($parameter['limit']); 
    	if(!empty($options['sort']) && !empty($options['order'])) $this->db->order_by($options['sort'],$options['order']);
		return $execute?$this->db->get():$this->db->_compile_select();
	}
	//SOAP�ӿ�
	function webservice($url,$ff,$arr=array(),$check=true){
		$client = new SoapClient(SOAP.$url.'.asmx?WSDL',array('encoding'=>'utf-8'));
		$header = new SoapHeader(SOAP_HEADER,'HTSoapHeader',array('UserName'=>'test','PassWord'=>'123456'));
		$client->__setSoapHeaders($header);
		$client->soap_defencoding = 'utf-8';
	    $client->decode_utf8 = false;
	    $client->xml_encoding = 'utf-8';
		$aryResult = $client->$ff($arr);
		return (array)$aryResult;

	}
	
	function webservice1($url,$ff,$arr=array(),$check=true){
		$client = new SoapClient('http://114.215.209.224:8088/'.$url.'.asmx?WSDL',array('encoding'=>'UTF8'));
		if($check){
			$header = new SoapHeader(SOAP_HEADER,'HTSoapHeader',array('UserName'=>'test','PassWord'=>'123456'));
			$client->__setSoapHeaders($header);
		}
		$client->soap_defencoding = 'utf-8';
	    $client->decode_utf8 = false;
	    $client->xml_encoding = 'utf-8';
		//$aryResult = $client->call($ff, $arr);
		$aryResult = $client->$ff($arr);
		return (array)$aryResult;

	}
	public function getSubCategory($pid,&$ids,$pidname='pid',$table){ 
		$arr=$this->get_all('*',array($pidname=>$pid),$table);
		if($arr==array()) return;
		else{
			foreach($arr as $v){
				$ids[]=$v['id'];
				$this->getSubCategory($v['id'],$ids,$pidname,$table);
			}
		}
	} 
	public function async($url, $params){
		foreach ($params as $key => &$val) {
			if(is_array($val)) $val = implode(',', $val);
			$post_params[] = $key.'='.urlencode($val);
		}
		$post_string = implode('&', $post_params);
		$parts=parse_url($url);
		$fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);
		$out = "POST ".$parts['path']." HTTP/1.1\r\n";
		$out.= "Host: ".$parts['host']."\r\n";
		$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out.= "Content-Length: ".strlen($post_string)."\r\n";
		$out.= "Connection: Close\r\n\r\n";
		if(isset($post_string)) $out.= $post_string;
		fwrite($fp, $out);
		fclose($fp);
	}
	public function curl_get($url){
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER,array('AuthGC: token=1234567890qwertyuiop'));
		//curl_setopt($ch, CURLOPT_HTTPHEADER,array('X-FORWARDED-FOR: 8.8.8.8','CLIENT-IP: 8.8.8.8'));
		curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
	public function curl_post($url,$data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0");
		curl_setopt($ch, CURLOPT_REFERER, "http://www.google.ca/");
		$guest_ip=$_SERVER["REMOTE_ADDR"];
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.$guest_ip, 'CLIENT-IP:'.$guest_ip));
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	public function push($fields){
		$this->ci->load->library('Huashang/mqtt',array('address'=>"localhost", 'port'=>1883,'clientid'=>'MQTT CLIENT'));
		if ($this->ci->mqtt->connect()) {
			$this->ci->mqtt->publish("u/demo",json_encode($fields),0);
			$this->ci->mqtt->close();
		}
	}
	public function status($s,$m){
		return array('status'=>$s,'msg'=>$m);
	}
	//XML转ARRAY
	public function xmlToarray($str){
		$res = @simplexml_load_string($str,NULL,LIBXML_NOCDATA);
		$res = json_decode(json_encode($res),true);
		return $res;
	}
	public function arraytoTree($rows, $id='id',$pid='pid',$child='childs',$root=0){  
		$tree = array();
        if(is_array($rows)){
			$array = array();
			foreach ($rows as $key=>$item){
				$array[$item[$id]] =& $rows[$key];
			}
			foreach($rows as $key=>$item){
				$parentId = $item[$pid];
				if($root == $parentId){
					$tree[] =&$rows[$key];
				}else{
					if(isset($array[$parentId])){
						$parent =&$array[$parentId];
						$parent[$child][]=&$rows[$key];
					}
				}
			}
		}
		return $tree;
	}
	//发送邮件
	public function sendmail($name,$to,$topic,$content){
		$config = Array(
			'protocol'  => 'smtp',
			'smtp_host' => 'ssl://smtp.qq.com',
			'smtp_port' => 465,
			'smtp_user' => 'support@168off.com',
			'smtp_pass' => 'eprgdip@521',
			'mailtype'  => 'html', 
			'newline'   => "\r\n",
			'crlf'      => "\r\n",
			'smtp_timeout'=>50,
		);
		$this->ci->load->library('email', $config);
		$this->ci->email->from('support@168off.com', $name);
		$this->ci->email->to($to);
		$this->ci->email->subject($topic);
		$this->ci->email->message($content);
		$this->ci->email->send();
		//echo $this->ci->email->print_debugger();
	}
	/** 通过IP查找地址 **/
	public function location($ip){
		$arr=json_decode(file_get_contents("http://api.map.baidu.com/location/ip?ak=3aaadcbeae9a481baf24e3ba767060ee&ip=$ip"),true);
		$data=array(
		'address'=>$arr['content']['address'],
		'detail'=>array(
			'province'=>$arr['content']['address_detail']['province'],
			'city'=>$arr['content']['address_detail']['city'],
			'district'=>$arr['content']['address_detail']['district'],
			'street'=>$arr['content']['address_detail']['street']
		),
		'geo'=>array('lat'=>$arr['content']['point']['x'],'lng'=>$arr['content']['point']['y'])
		);
		return $data;
	}
	
	/**********************导出************************************/
	/*** 导出EXCEL(修正版)
	 * 可以生成多个工作表，多工作表示例请参阅后台订单, 单工作表示例请参阅后台违禁词
	**/
	function export($title,$rs=array()){
		if($rs==array()) return;
		$this->ci->load->library('Huashang/PHPExcel');
		$alpha=array_merge(array_merge(range('A','Z'),array_map(create_function('$v','return "A$v";'),range('A','Z'))),array_map(create_function('$v','return "B$v";'),range('A','Z')));  
		$color=array('FF0000','00FF00','993300','00FFFF','008000','008080','9999FF','993366','0066CC','FF6600','FF00FF','333399','333333','99CC00','FFCC00','FF9900','660066','800000','800080','333300');
		foreach($rs as $k=>$v){
			if($k!=0) $this->ci->phpexcel->createSheet();
			$this->ci->phpexcel->setActiveSheetIndex($k);
			$sheet = $this->ci->phpexcel->getActiveSheet();
			$sheet->setTitle($v['name']);
			$fields=array_keys(array_map(create_function('$v','return array_keys($v);'),$v['fields']));
			foreach($fields as $k=>$s){
				$arr[$s]=$alpha[$k];
				$sheet->getColumnDimension($alpha[$k])->setWidth(15);
				$sheet->setCellValue($alpha[$k]."1",is_array($v['fields'][$s])?$v['fields'][$s][0]:$v['fields'][$s]);
				$sheet->getStyle($alpha[$k]."1")->applyFromArray(array('font'=>array('bold'=>true,'color'=>array('rgb' => 'FFFFFF')),'fill'=>array('type'=>PHPExcel_Style_Fill::FILL_SOLID,'color'=>array('rgb' =>empty($color[$k])?'FF0000':$color[$k]))));
			}
			foreach($v['data'] as $k=>$s){
				foreach($s as $i=>$o){
					if(in_array($i,$fields)){
						if(is_array($v['fields'][$i])){
							if(!empty($v['fields'][$i][1])){
								$func=create_function('$value,$row',$v['fields'][$i][1].';');
								$t=$func($o,$s);
							}else $t=$o;
						}else $t=$o;
						$sheet->setCellValue($arr[$i].($k+2),(string)$t);
					}
				}
			}
		}
		$this->ci->phpexcel->setActiveSheetIndex(0);
		$writer = new PHPExcel_Writer_Excel5($this->ci->phpexcel);
		header('Content-type: application/vnd.ms-excel');
		header("Content-Disposition:attachment; filename=".(empty($title)?'无标题':$title).".xls"); 
		$writer->save('php://output'); 
	}
	/** 导出CSV
	 * 支持大数据
	 **/
	public function exportCSV($title,$head=array(),$table,$args=array(),$parameter=array(),$def_sort='b.id',$sum='*'){
		header('Content-Type: application/vnd.ms-excel;charset=utf-8');
		header('Content-Disposition: attachment;filename="'.$title.'.csv"');
		header('Cache-Control: max-age=0');
		$fp = fopen('php://output', 'a');
		fwrite($fp,"\xEF\xBB\xBF");//写入BOOM
		foreach($head as $i=>$v){
			$headline[$i] = is_array($v)?array_shift($v):$v;
		}
		fputcsv($fp,$headline);
		$this->open($table);
		$pagesize=50;
		$arr=$this->get_list($args,$parameter,$def_sort,$sum);
		$total=$arr['total_rows'];
		$data=$arr['result'];
		$pages=intval($total/$pagesize);
		if($total%$pagesize) $pages++;
		
		$cnt = 0;
		$limit = 100000;
		for($i=1;$i<=$pages;$i++){
			$_POST['size']=$pagesize;
			$_POST['page']=$i;
			$arr=$this->get_list($args,$parameter,$def_sort,$sum);
			$data=$arr['result'];
			foreach($data as $k=>$v){
				$dataset[]=$v;
				if($table=='order'){
					$_arr=$this->get_all('*',array('oid'=>$v['cid']),'order_detail');
					foreach($_arr as $t=>$s){
						$row=$v;
						$row['cid'].="-$s[id]";
						$row['user_name']=$row['uid']=$row['order_time']=$row['order_id']=$row['link_type']=$row['shop_id']=$row['shop_name']=$row['u_email']=$row['nick_name']=$row['u_mobile']=$row['member_rebate_checked']='';
						$row['member_rebate']=$s['member_rebate'];
						$row['shop_return_rate_uncheck']=$s['current_return_rate'];
						$row['addtime']=$s['add_time'];
						$row['check_time']=$s['check_time'];
						$row['u_qq']=$row['ad_customer_id']=$row['feedback']='';
						$row['uniq_id']=$s['uniq_id'];
						$row['goods_category']=$s['goods_category'];
						$dataset[]=$row;
					}
				}
			}
			
			foreach($dataset as $k=>$v){
				$cnt++;
				if($limit == $cnt){ 
					ob_flush();
					flush();
					$cnt = 0;
				}
				$row=array();
				foreach($head as $d=>$s){
					if(in_array($d,array_keys($v))){
						if(is_array($s)){
							$func=create_function('$value,$row',$s[1].';');
							$row[$d]=$func($v[$d],$v);
						}else $row[$d]=(string)$v[$d];
					}else $row[$d]='';
				}
				fputcsv($fp, $row);
			}
		}
		fclose($fp);
	}
	/***导入**/
	//导入
	public function import($file){
		$this->ci->load->library('PHPExcel');
		require_once "Excel/reader.php";
		$reader= new Spreadsheet_Excel_Reader();
		$reader->setOutputEncoding('utf-8');
		$reader->read($file);
		$cate = $this->ci->input->post('cate');
		foreach($reader->sheets[0]['cells'] as $k=>$v){
			if($k==1||$k==2) continue;
			if($cate==1){
				$item = array(
					'proname' => $v[2],
					'danwei'  => $v[3],
					'num'     => $v[4],
					'jcdate'  => PHPExcel_Shared_Date::ExcelToPHP($v[5]),
					'cate'    => $cate,
				);
			}else if($cate==2 || $cate==3){
				$item = array(
					'sn'        => $v[2],
					'proname'   => $v[3],
					'address'   => $v[4],
					'danwei'    => $v[5],
					'supplier'  => $v[6],
					'cert_code' => $v[7],
					'jcdate'    => PHPExcel_Shared_Date::ExcelToPHP($v[8]),
					'cate'      => $cate,
				);
			}else if($cate=4){
				$item = array(
					'proname' => $v[2],
					'danwei'  => $v[3],
					'jcdate'  => PHPExcel_Shared_Date::ExcelToPHP($v[4]),
					'cate'    => $cate,
				);
			}
			if($item['proname']) $arr[]=$item;
		}
		$this->db->insert_batch('baogao', $arr); 
		return $this->status(true,$arr);
	}
	
	//无限分级
	function data2tree($data, $root=0, $cid='id', $pid='pid', $child='children', $_parent='', $_id=''){
		$tree = array();
		$_temp = array();
		foreach($data as $key=>$val){
			if(!empty($_parent) && $_parent==$val[$cid]) continue;
			$_temp[$val[$cid]] = &$data[$key];
		}
		foreach($data as $key=>$val){
			$parentId = $val[$pid];   //上级id
			if($root == $parentId){   //如果上级id 等于根id
				if(empty($_id) || $_id!=$val[$cid]) $tree[] = &$data[$key];   //那么 添加到tree里面
			}else{
				if(isset($_temp[$parentId])){
					$parent = &$_temp[$parentId]; 
					$parent[$child][] = &$data[$key];
				}
			}
		}
		return $tree;
	}
	public function pinyin($text,$concat='-'){
		require_once('ChinesePinyin.class.php'); 
		$Pinyin = new ChinesePinyin();
		$result = $Pinyin->TransformWithoutTone(strip_tags($text),$concat);
		return substr($result,0,strlen($result));
	}
	//压缩图片
	public function scaleImg($src,$pWidth=800){
		if(stristr($src,'.jpg') || stristr($src,'.jpeg') || stristr($src,'.png') || stristr($src,'.gif')){ 
			$info  = getimagesize($src);
			$width = $info[0];
			$height= $info[1]; 
			$mime  = array_pop($info); 
			if($width>$pWidth){//宽度超过指定宽度时进行压缩
				$w = $pWidth;
				$h = intval($w*$height/$width);
				$temp_img=imagecreatetruecolor($w,$h);
				if(stristr($mime,'jpeg')) $im = imagecreatefromjpeg($src);
				if(stristr($mime,'png'))  $im = imagecreatefrompng($src);
				if(stristr($mime,'gif'))  $im = imagecreatefromgif($src);
				imagecopyresampled($temp_img,$im,0,0,0,0,$w,$h,$width,$height);
				imagejpeg($temp_img,$src, 100);
				imagedestroy($im);
			}
		}
	}
	//保存远程图片
	public function saveRemotePhoto($url,$dir='../uploads/'){
		$ch  = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
		$raw = curl_exec($ch);
		curl_close($ch);
		$rootDir = $dir.'image/'.date('Y');
		if(!file_exists($rootDir)) @mkdir($rootDir);
		$targetDir = $rootDir.'/'.date('md');
		if(!file_exists($targetDir)) @mkdir($targetDir);
		$saveto = $targetDir.DIRECTORY_SEPARATOR.md5(uniqid()).'.'.array_pop(explode('.',$url));
		$fp = fopen($saveto,'x');
		fwrite($fp, $raw);
		fclose($fp);
		return '{"jsonrpc":"2.0", "result":"'.str_replace('../','',$saveto).'"}';
	}
	//快递查询(新版)
	public function express($e,$sn,$order){
		$url = "http://wap.kuaidi100.com/wap_result.jsp?rand=".time()."&id=$e&fromWeb=null&postid=$sn";
		$c   = $this->curl_get($url);
		preg_match_all('/<p>\&middot\;(.*?)<\/p>/is',$c,$arr);
		$isComplete=false;
		$routine=array();
		foreach($arr[1] as $v){
			if(stristr($v,'已收件')||stristr($v,'已签收')) $isComplete=true;
			$a = explode('<br />',$v);
			if(!trim($a[0])||!trim($a[1])) continue;
			$routine[]=array(
				'time'=>trim($a[0]),
				'ftime'=>trim($a[0]),
				'context'=>trim($a[1])
			);
		}
		//if($isComplete) $this->db->update('order',array('ship_status'=>3), array('order_sn'=>$order));
		
		$f   = 'uploads/file/delivery.json';
		$j   = file_get_contents($f);
		if(!$j) $j = file_get_contents("../$f");
		foreach(json_decode($j,true) as $v){
			if($v['code']==$e){
				$e=$v;break;
			}
		}
		return array(
			'status' =>$isComplete?'已签收':'在途',
			'fuzhi_str' =>$routine,
			'carrier'=>$e,
			'sn' =>$sn,
		);
	}
}